package com.jci.vsd.activity.enterprise;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.jci.vsd.R;
import com.jci.vsd.activity.BaseActivity;
import com.jci.vsd.activity.LoginActivity;
import com.jci.vsd.bean.enterprise.MembersBean;
import com.jci.vsd.bean.enterprise.ProducerAddBean;
import com.jci.vsd.bean.enterprise.ProducerSettingInfoBean;
import com.jci.vsd.network.control.ProducerManageControl;
import com.jci.vsd.observer.CommonDialogObserver;
import com.jci.vsd.observer.RxHelper;
import com.jci.vsd.utils.Loger;
import com.jci.vsd.utils.TimePickerUtils;
import com.jci.vsd.view.widget.SimpleToast;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cn.addapp.pickers.listeners.OnMoreItemPickListener;
import cn.addapp.pickers.picker.LinkagePicker;
import io.reactivex.Observable;

/**
 * Created by liqing on 18/7/3.
 * 新增审批流程
 * 1.先判断是否可配置（有可配置的审批部门&&可配置流程&&可配置审批人）
 * 2.审批流程选择 左列表示：为当前配置第几审批，右边是其配置的上级审批流程
 * 例如：现有1级审批：1a ,二级审批2a和2b,则新增审批流程M时候，可以为其选择审批流程2or3
 * 如果选择2，则右边上级审批就是1 级审批的1a;如果选择了3，则右边是2级审批的 2a和2b
 */

public class
ProducerAddActivity extends BaseActivity {

    private static final int REQUEST_PERSON = 1100;
    @BindView(R.id.edt_producer_name)
    EditText edtProducerName;

    @BindView(R.id.tv_producer_department)
    TextView tvProducerDepart;

    @BindView(R.id.tv_producer_order)
    TextView tvProducerOrder;


    @BindView(R.id.tv_producer_person)
    TextView tvProducerPerson;
    @BindView(R.id.tv_sure)
    TextView tvSure;

    @BindView(R.id.button_back)
    ImageButton backBtn;
    @BindView(R.id.textview_title)
    TextView titleTxt;
    private List<ProducerSettingInfoBean.AvldptsBean> listDeparts = new ArrayList<>();// 可配置的部门
    private List<ProducerSettingInfoBean.AvlusersBean> listApprover = new ArrayList<>();//可配置人员
    List<Integer> selectDepsId = new ArrayList<>();//已选择的审批部门id
    String[] itemsDeparts = new String[]{""};//已选择的审批部门名称
    String[] itemsApprovers = new String[]{""};//可配置的审批人名称
    private int selectApproverId;//选择的审批人id
    private int sort;//审批级别
    private List<String> firstList = new ArrayList<>();//审批流程配置第一列的数据集合,
    private int parentProducerId;//审批流程父亲节点的id
    private int selectProducerId;//选中的审批流程id
    private List<ProducerSettingInfoBean.ChkpntsBean> producersList = new ArrayList<>();//所有的审批流程数据
    List<ProducerSettingInfoBean.ChkpntsBean.FathsBean> fathsBeans = new ArrayList<>();//父节点的审批数据
    private String selectDepartName = "";//选择的部门名称
    private Boolean isSet;//是否可配置
    Boolean hasDpts = false; //是否有可选择的审核部门
    Boolean hasProducer = false;//是否可配置审批流程
    Boolean hasApprovals = false;//可选择的审核人
    private List<String> selectNames = new ArrayList<>();


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_producer_edit);
        initViewEvent();
        getProducerSettingInfo();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == REQUEST_PERSON) {
            Bundle bundle = data.getExtras();
            MembersBean userBean = (MembersBean) bundle.getSerializable("user");
            tvProducerPerson.setText(userBean.getName());

        }
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.tv_sure:
                if (isSet) {
                    checkData();
                } else {
                    SimpleToast.toastMessage("暂不可配置流程", Toast.LENGTH_SHORT);
                }

                break;
            case R.id.tv_producer_department:
                if (listDeparts.size() == 0) {
                    SimpleToast.toastMessage("暂无可配置部门", Toast.LENGTH_SHORT);
                } else {
                    showMultiChoiceDialog();
                }

                break;
            case R.id.tv_producer_order:
                // sort =2: 最低可配置审批流程2（审批流程sort=1：老板审批；然后往下配置流程2，再配置审批流程3）
                if (hasProducer) {
                    if (sort == 2) {
                        List<String> list = new ArrayList<>();
                        list.add("2");
                        selectProducerId = 2;
                        TimePickerUtils.getInstance().onListPicker(ProducerAddActivity.this, list, tvProducerOrder);
                    } else {
                        onLinkagePicker(tvProducerOrder, 3);
                    }

                } else {
                    SimpleToast.toastMessage("暂无可配置流程", Toast.LENGTH_SHORT);
                }


                break;
            case R.id.tv_producer_person:
                Loger.e("click--tv_producer_person");
                if (listApprover.size() == 0) {
                    SimpleToast.toastMessage("暂无可配置人员", Toast.LENGTH_SHORT);
                } else {
                    showSingleChoiceDialog();
                }

                break;
            default:
                break;
        }
    }

    //可配置的审批流程（左审批级别，右审批级别对应下的审批名称）
    public void onLinkagePicker(final TextView view, final int i) {

        final LinkagePicker.DataProvider provider = new LinkagePicker.DataProvider() {

            @Override
            public boolean isOnlyTwo() {
                return true;
            }

            @Override
            public List<String> provideFirstData() {
                Loger.e("---provideFirstData--");
                firstList.clear();
                for (int i = 0; i <= sort - 2; i++) {
                    firstList.add(i + 2 + "");
                    Loger.e("firstList" + firstList.get(i));
                }
                return firstList;
            }


            @Override
            public List<String> provideSecondData(int firstIndex) {
                Loger.e("---provideSecondData--");
                long start = System.currentTimeMillis();
                long end = 0;
//                //二级下面的KeyValueBean（即 sort 对应的faths : [{"name":"领导审批","id":2}]）
                List<String> secondList = new ArrayList<>();
                selectProducerId = Integer.valueOf(firstList.get(firstIndex));
                Loger.e("--selectProducerId-" + selectProducerId);
                for (int i = 0; i < producersList.size(); i++) {

                    if (producersList.get(i).getSort() == selectProducerId - 1) {
                        fathsBeans.clear();
                        fathsBeans.addAll(producersList.get(i).getFaths());
                        break;
                    }
                }

                //
                for (int j = 0; j < fathsBeans.size(); j++) {
                    secondList.add(fathsBeans.get(j).getName());
                }
                end = System.currentTimeMillis();
                Loger.e("provideSecondData--" + "end-start=" + (end - start));
                return secondList;

            }

            @Override
            public List<String> provideThirdData(int firstIndex, int secondIndex) {
                //这里用不到三级
                Loger.e("---secondIndex--" + secondIndex);
                ArrayList<String> thirdList = new ArrayList<>();
//                for (int i = 1; i <= (firstIndex == 0 ? 12 : 24); i++) {
//                    String str = DateUtils.fillZero(i) + "third";
//                    if (firstIndex == 0) {
//                        str += "￥";
//                    } else {
//                        str += "$";
//                    }
//                    thirdList.add(str);
//                }
                return thirdList;
            }

        };

        LinkagePicker picker = new LinkagePicker(this, provider);
        picker.setCanLoop(true);
        picker.setSelectedIndex(0, 0);
        //picker.setSelectedItem("12", "9");
        picker.setOnMoreItemPickListener(new OnMoreItemPickListener<String>() {

            @Override
            public void onItemPicked(String first, String second, String third) {
                Loger.e(first + "-" + second + "-" + third);
                for (int i = 0; i < fathsBeans.size(); i++) {
                    if (fathsBeans.get(i).getName().equals(second)) {
                        parentProducerId = fathsBeans.get(i).getId();
                        Loger.e("---fathId--" + parentProducerId);
                    }

                }
                view.setText("" + first);

            }

        });

        picker.show();
    }


    private void checkData() {
        String name = edtProducerName.getText().toString();
        String level = tvProducerOrder.getText().toString();

        String depart = tvProducerDepart.getText().toString();
        String person = tvProducerPerson.getText().toString();

        if (TextUtils.isEmpty(name)) {
            SimpleToast.toastMessage("审批名称不可为空", Toast.LENGTH_LONG);
            edtProducerName.requestFocus();
            return;
        }

        if (TextUtils.isEmpty(level)) {
            SimpleToast.toastMessage("审批流程不可为空", Toast.LENGTH_LONG);

            return;
        }
        if (selectDepsId.size() == 0) {
            SimpleToast.toastMessage("审批部门不可为空", Toast.LENGTH_LONG);

            return;
        }
        if (TextUtils.isEmpty(selectApproverId + "")) {
            SimpleToast.toastMessage("审批人不可为空", Toast.LENGTH_LONG);

            return;
        }


        ProducerAddBean producerBean = new ProducerAddBean();
        producerBean.setName(name);
        producerBean.setFath(parentProducerId);
        producerBean.setSort(selectProducerId);
        producerBean.setChecker(selectApproverId);
        producerBean.setDpts(selectDepsId);
        addProducerItem(producerBean);
    }

    @Override
    protected void initViewEvent() {
        tvSure.setOnClickListener(this);
        tvProducerOrder.setOnClickListener(this);
        tvProducerDepart.setOnClickListener(this);
        tvProducerPerson.setOnClickListener(this);
        backBtn.setOnClickListener(this);
        titleTxt.setText(getResources().getString(R.string.producer_add));
    }

    //增加审批流程
    private void addProducerItem(ProducerAddBean requestBean) {
        Observable<Boolean> observable = new ProducerManageControl().addProducer(requestBean);
        CommonDialogObserver<Boolean> observer = new CommonDialogObserver<Boolean>(this) {
            @Override
            public void onNext(Boolean aBoolean) {
                super.onNext(aBoolean);
                if (aBoolean) {
                    SimpleToast.toastMessage("添加成功", Toast.LENGTH_SHORT);
                    toActivity(ProducerManageActivity.class);
                    finish();

                }
            }

            @Override
            public void onError(Throwable t) {
                super.onError(t);
                if (t.getMessage().equals("401"))

                    SimpleToast.toastMessage("登录超时，请重新登录", Toast.LENGTH_LONG);
                exit();
                toActivity(LoginActivity.class);
            }
        };
        RxHelper.bindOnUIActivityLifeCycle(observable, observer, ProducerAddActivity.this);
    }

    //获取可配置流程的的参数
    private void getProducerSettingInfo() {

        Observable<ProducerSettingInfoBean> observable = new ProducerManageControl().getProducerSettingInfo();
        CommonDialogObserver<ProducerSettingInfoBean> observer = new CommonDialogObserver<ProducerSettingInfoBean>(this) {
            @Override
            public void onNext(ProducerSettingInfoBean bean) {
                super.onNext(bean);
                sort = bean.getSortavl();
                //sort =2，只要配置boss下面一级。

                //可选择的审核部门
                if (bean.getAvldpts() != null && bean.getAvldpts().size() > 0) {
                    hasDpts = true;
                    //setting department
                    listDeparts.clear();
                    listDeparts.addAll(bean.getAvldpts());

                    //赋值给 department items
                    itemsDeparts = new String[listDeparts.size()];
                    for (int i = 0; i < listDeparts.size(); i++) {
                        itemsDeparts[i] = listDeparts.get(i).getName();

                    }

                }
                //可选择的审批流程
                if (bean.getChkpnts() != null && bean.getChkpnts().size() > 0) {
                    hasProducer = true;
                    producersList.clear();
                    producersList.addAll(bean.getChkpnts());
                    fathsBeans.clear();
                    fathsBeans.addAll(producersList.get(0).getFaths());
                    parentProducerId = fathsBeans.get(0).getId();
                    Loger.e("---parentProducerId" + parentProducerId);
                }

                //可选择的审核人
                if (bean.getAvlusers() != null && bean.getAvlusers().size() > 0) {
                    hasApprovals = true;
                    listApprover.clear();
                    listApprover.addAll(bean.getAvlusers());
                    itemsApprovers = new String[listApprover.size()];
                    for (int i = 0; i < listApprover.size(); i++) {
                        itemsApprovers[i] = listApprover.get(i).getName();
                        Loger.e("approver-" + listApprover.get(i).getName());

                    }
                }

                if (hasDpts && hasProducer && hasApprovals) {
                    SimpleToast.toastMessage("流程可配置信息获取成功", Toast.LENGTH_SHORT);
                    isSet = true;
                } else {
                    SimpleToast.toastMessage("可配置信息不完整，暂不可添加", Toast.LENGTH_SHORT);
                    isSet = false;
                }

            }

            @Override
            public void onError(Throwable t) {
                super.onError(t);
                if (t.getMessage().equals("401")) {
                    SimpleToast.toastMessage("登录超时，请重新登录", Toast.LENGTH_LONG);
                    exit();
                    toActivity(LoginActivity.class);
                }


            }
        };
        RxHelper.bindOnUIActivityLifeCycle(observable, observer, ProducerAddActivity.this);
    }

    List<String> selectDptIdStr = new ArrayList<>();

    //可配置部门多选框
    private void showMultiChoiceDialog() {

        selectDepsId.clear();
        selectDptIdStr.clear();
        selectNames.clear();
        selectDepartName = "";
        AlertDialog dialog = new AlertDialog.Builder(this).setTitle("多选对话框")
//                .setNegativeButton("取消", null).setPositiveButton("确定", null)
                .setMultiChoiceItems(itemsDeparts, null, new DialogInterface.OnMultiChoiceClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which, boolean isChecked) {

                        if (isChecked) {
                            selectDptIdStr.add(listDeparts.get(which).getDpt() + "");
                            selectNames.add(itemsDeparts[which]);

                        } else {
                            selectDptIdStr.remove(listDeparts.get(which).getDpt() + "");
                            selectNames.remove(itemsDeparts[which]);
                        }

                        selectDepsId.clear();
                        //部门ids
                        if (selectDptIdStr.size() > 0) {

                            for (int i = 0; i < selectDptIdStr.size(); i++) {
                                Loger.e("---IdStr:" + selectDptIdStr.get(i));
                                selectDepsId.add(Integer.valueOf(selectDptIdStr.get(i)));

                            }
                        }

                        for (int i = 0; i < selectDepsId.size(); i++) {
                            Loger.e("---selectDepsId:" + selectDepsId.get(i));

                        }

                        String name = "";
                        if (selectNames.size() != 0) {
                            for (int i = 0; i < selectNames.size(); i++) {
                                Loger.e("---selectName:" + selectNames.get(i));
                                name = name + selectNames.get(i);
                                Loger.e("--name" + name);
                            }
                        }
                        tvProducerDepart.setText(name);


                    }


                })
                .setNegativeButton(getResources().getString(R.string.cancel), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Loger.e("----cancel---");
                        tvProducerDepart.setText("");
                        selectDepsId.clear();

                    }
                })

                .setPositiveButton(getResources().getString(R.string.sure), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Loger.e("----sure---sure----");


                    }
                })

                .create();
        dialog.show();

    }

    //审批人选择单选框singleChoicea
    private void showSingleChoiceDialog() {

        AlertDialog dialog = new AlertDialog.Builder(this).setTitle("单选对话框").setIcon(R.drawable.ic_image)
                .setSingleChoiceItems(itemsApprovers, -1, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        Loger.e("choose-whitch--" + which);
                        tvProducerPerson.setText(itemsApprovers[which]);
                        selectApproverId = listApprover.get(which).getUid();
                        Loger.e("choose-selectApproverId--" + selectApproverId);
                        dialog.dismiss();

                    }
                }).create();
        dialog.show();

    }


}
